<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" title="系统参数配置管理">
        <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
          <template #statusSlot="{ model, field }">
            <n-input v-model:value="model[field]" />
          </template>
        </BasicForm>
      </n-card>
    </div>
    <n-card :bordered="false" class="mt-4 proCard">
      <BasicTable :columns="columns" :request="loadDataTable" :row-key="(row) => row.id" ref="actionRef"
        :actionColumn="actionColumn" @update:checked-row-keys="onCheckedRow" :bordered="false">
        <template #tableTitle>
          <n-space>
            <n-button type="primary" :on-click="handleEdit.bind(null, {}, true)">
              <template #icon>
                <n-icon>
                  <PlusOutlined />
                </n-icon>
              </template>
              添加参数配置
            </n-button>
            <n-button type="primary" :loading="btnLoading" :on-click="refreshCache">
              <template #icon>
                <n-icon>
                  <SyncOutlined />
                </n-icon>
              </template>
              刷新配置缓存
            </n-button>
          </n-space>
        </template>
        <template #action>
          <TableAction />
        </template>
      </BasicTable>
    </n-card>

    <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" :title="editTitle" style="border-radius: 8px;">
      <n-form :model="fromValues" :rules="rules" ref="formRef" label-placement="top" :label-width="120" class="py-4">
        <n-form-item label="配置名称" path="configExplain">
          <n-input maxlength="150" show-count placeholder="请输入配置名称" v-model:value="fromValues.configExplain" />
        </n-form-item>
        <n-form-item label="配置CODE" path="configCode">
          <n-input maxlength="32" show-count placeholder="请输入配置CODE" v-model:value="fromValues.configCode" />
        </n-form-item>
        <n-form-item label="配置值" path="configValue">
          <n-input maxlength="300" show-count placeholder="请输入配置值" v-model:value="fromValues.configValue" />
        </n-form-item>
        <n-form-item label="状态" path="deleted">
          <n-select v-model:value="fromValues.deleted" filterable placeholder="请选择状态" :options="deletedOptions" />
        </n-form-item>
      </n-form>
      <div style="justify-content: end;display: flex;">
        <n-space>
          <n-button ghost icon-placement="left" @click="handleCloseModel">
            取消
          </n-button>
          <n-button type="primary" :loading="formBtnLoading" @click="confirmForm">提交</n-button>
        </n-space>
      </div>
    </n-modal>

    <!-- 重置密码，查看密码 -->
    <n-modal v-model:show="showPassword" :show-icon="false" preset="dialog" :title="isShowPassword ? '查看密码' : '重置密码'">
      <div v-if="isShowPassword">{{ configValue }}</div>
      <n-input v-if="!isShowPassword" type="password" showPasswordOn="click" maxlength="150" show-count
        placeholder="请输入配置值" v-model:value="configValue" />
      <div style="justify-content: end;display: flex;margin-top: 15px;">
        <n-space>
          <n-button ghost icon-placement="left" @click="handleCancelShowPassword">
            取消
          </n-button>
          <n-button v-if="!isShowPassword" type="primary" :loading="formBtnLoading" @click="confirmValue">提交</n-button>
        </n-space>
      </div>
    </n-modal>

    <!-- 更换图片 -->
    <n-modal v-model:show="changePicModel" :show-icon="false" preset="dialog" title="更换图片">
      <BasicUpload :action="`${uploadUrl}/moss-cloud-resource/resource/uploadFile`" :headers="uploadHeaders"
        :data="{ type: 0 }" name="file" :width="100" :height="100" @upload-change="uploadPictureChange"
        v-model:value="picture" :maxNumber="1" helpText="单个文件不超过20MB，最多只能上传1个文件" />
      <div style="justify-content: end;display: flex;margin-top: 15px;">
        <n-space>
          <n-button ghost icon-placement="left" @click="handleCancelPicModel">
            取消
          </n-button>
          <n-button v-if="!isShowPassword" type="primary" :loading="formBtnLoading" @click="confirmPicture">提交</n-button>
        </n-space>
      </div>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, h } from 'vue';
import { useMessage, useDialog, type FormRules } from 'naive-ui';
import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
import { BasicTable, TableAction } from '@/components/Table';
import { getSystemParams, saveOrUpdate, deleteSystemConfig, loadSystemConfig, showPasswordApi, updateValue } from '@/api/system/param';
import { columns } from './columns';
import { PlusOutlined, DeleteOutlined, EditOutlined, SyncOutlined } from '@vicons/antd';
import { ResultEnum } from '@/enums/httpEnum';
import { deletedOptions } from '@/utils/convert';
import { encrypt } from '@/utils/CryptoUtil';
import { BasicUpload } from '@/components/Upload';
import { useGlobSetting } from '@/hooks/setting';
import { useUser } from '@/store/modules/user';
const globSetting = useGlobSetting();
const { uploadUrl } = globSetting;
const userStore = useUser();
const message = useMessage();
const actionRef = ref();
const isAdd = ref(true);
const showModal = ref(false);
const formBtnLoading = ref(false);
const btnLoading = ref(false);
const editTitle = ref('');
const dialog = useDialog();
const formRef: any = ref(null);
const showPassword = ref(false);
const configValue = ref('');
const isShowPassword = ref(false);
const currentConfig = ref<Recordable>({});
const changePicModel = ref(false);
const picture: any = ref([]);
const uploadHeaders = reactive({
  timestamp: new Date().getTime(),
  Authorization: 'Bearer ' + userStore.getToken,
});
let fromValues = reactive({
  id: null,
  configExplain: '',
  configCode: '',
  configValue: '',
  deleted: null
});
/**
 * 表格查询参数定义
 */
const schemas: FormSchema[] = [
  {
    field: 'configExplain',
    component: 'NInput',
    label: '配置名称',
    componentProps: {
      placeholder: '请输入配置名称',
    },
  },
  {
    field: 'configCode',
    component: 'NInput',
    label: '配置CODE',
    componentProps: {
      placeholder: '请输入配置CODE',
      showButton: false,
    },
  },
  {
    field: 'deleted',
    component: 'NSelect',
    label: '状态',
    componentProps: {
      placeholder: '请选择状态',
      options: deletedOptions,
    },
  },
];
const rules: FormRules = {
  configExplain: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入名称',
  },
  configCode: [
    {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入地址',
    },
    { pattern: /^[^\u4e00-\u9fa5]+$/, trigger: ['blur', 'input'], message: '不能输入中文' },
  ],
  configValue: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入配置值',
  },
  deleted: {
    type: 'number',
    required: true,
    trigger: ['blur', 'select'],
    message: '请选择状态',
  },
};
/**
 * 创建操作栏工具
 * @param record 
 */
function createActions(record) {
  return [
    {
      label: '删除',
      type: 'error',
      // 配置 color 会覆盖 type
      color: 'red',
      icon: DeleteOutlined,
      onClick: handleDelete.bind(null, record),
      // 根据业务控制是否显示 isShow 和 auth 是并且关系
      ifShow: () => {
        return true;
      },
      // 根据权限控制是否显示: 有权限，会显示，支持多个
      //auth: ['basic_list'],
    },
    {
      label: '编辑',
      type: 'primary',
      icon: EditOutlined,
      onClick: handleEdit.bind(null, record, false),
      ifShow: () => {
        return true;
      },
      //auth: ['basic_list'],
    },
  ];
}
/**
 * 表格查询注册
 */
const [register, { getFieldsValue }] = useForm({
  gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
  labelWidth: 80,
  schemas,
});
/**
 * 定义操作栏
 */
const actionColumn = reactive({
  width: 250,
  title: '操作',
  key: 'action',
  fixed: 'cen',
  render(record) {
    return h(TableAction as any, {
      style: 'text',
      actions: createActions(record),
      dropDownActions: [
        {
          label: '查看密码',
          key: 'DEFAULT_PASSWORD',
          // 根据业务控制是否显示: 非enable状态的不显示启用按钮
          ifShow: () => {
            return record.configCode === 'DEFAULT_PASSWORD' || record.configCode === 'RESET_PASSWORD' ? true : false;
          },
        },
        {
          label: '重置密码',
          key: 'RESET_PASSWORD',
          ifShow: () => {
            return record.configCode === 'DEFAULT_PASSWORD' || record.configCode === 'RESET_PASSWORD' ? true : false;
          },
        },
        {
          label: '更换LOGO',
          key: 'SYSTEM_LOGO',
          ifShow: () => {
            return record.configCode === 'SYSTEM_LOGO' ? true : false;
          },
        },
        {
          label: '更换头像',
          key: 'DEFAULT_USER_PHOTO',
          ifShow: () => {
            return record.configCode === 'DEFAULT_USER_PHOTO' ? true : false;
          },
        },
        {
          label: '更换背景',
          key: 'MNG_LOGIN_NG_IMG',
          ifShow: () => {
            return record.configCode === 'MNG_LOGIN_NG_IMG' ? true : false;
          },
        },
        {
          label: '更换广告',
          key: 'MNG_LOGIN_AV',
          ifShow: () => {
            return record.configCode === 'MNG_LOGIN_AV' ? true : false;
          },
        },
      ],
      select: (key) => {
        if (key === 'DEFAULT_PASSWORD') {
          showPasswordModel(record, true)
        } else if (key === 'RESET_PASSWORD') {
          showPasswordModel(record, false)
        } else {
          handlechangePicModel(record);
        }
      },
    });
  },
});
/**
 * 获取分页数据
 * @param res 
 */
const loadDataTable = async (res: any) => {
  return await getSystemParams({ ...getFieldsValue(), ...res });
};
/**
 * 查询
 */
function handleSubmit() {
  reloadTable();
}
/**
 * 重置查询
 */
function handleReset() {
  reloadTable();
}
/**
 * 选中的行
 * @param rowKeys 
 */
function onCheckedRow(rowKeys: any[]) {
  console.log(rowKeys);
}
/**
 * 刷新表格
 */
function reloadTable() {
  actionRef.value.reload();
}
function resetFrom() {
  fromValues = Object.assign(fromValues, {
    id: null,
    configExplain: '',
    configCode: '',
    configValue: '',
    deleted: null
  });
}
/**
 * 新增编辑提交数据
 * @param e 
 */
function confirmForm(e: any) {
  e.preventDefault();
  formRef.value.validate(async (errors) => {
    if (!errors) {
      formBtnLoading.value = true;
      const data = await saveOrUpdate(fromValues);
      if (data.code !== ResultEnum.SUCCESS) {
        const resultMsg = (data.data !== null || data.data !== '') ? data.data : '';
        message.error(data.mesg + '-' + resultMsg);
      }
      if (data.code === ResultEnum.SUCCESS) {
        message.success(data.mesg);
        showModal.value = false;
        resetFrom();
        reloadTable();
      }
      formBtnLoading.value = false;
    } else {
      message.error('请填写完整信息');
    }
    formBtnLoading.value = false;
  });
}
/**
 * 新增编辑打开model
 * @param record 
 * @param addStatus 
 */
function handleEdit(record: Recordable, addStatus: boolean) {
  showModal.value = true;
  isAdd.value = addStatus;
  if (addStatus) {
    editTitle.value = `新增参数配置`;
  } else {
    editTitle.value = `编辑 ${record.configExplain}`;
    fromValues = Object.assign(fromValues, record);
  }
}
/**
 * 新增编辑关闭model
 */
function handleCloseModel() {
  resetFrom();
  showModal.value = false;
}
/**
 * 删除确认
 * @param record 
 */
function handleDelete(record: Recordable) {
  dialog.warning({
    title: '警告',
    content: `确定删除${record.configExplain}吗？`,
    positiveText: '确定',
    negativeText: '取消',
    style: "border-radius: 8px;",
    //position: fixed; left: 40%; top: 100px;
    onPositiveClick: async () => {
      const data = await deleteSystemConfig({ id: record.id });
      if (data.code !== ResultEnum.SUCCESS) {
        const resultMsg = (data.data !== null || data.data !== '') ? data.data : '';
        message.error(data.mesg + '-' + resultMsg);
      }
      if (data.code === ResultEnum.SUCCESS) {
        message.success(data.mesg);
        showModal.value = false;
        reloadTable();
      }
    },
  })
}
function refreshCache() {
  btnLoading.value = true;
  setTimeout(async () => {
    const data = await loadSystemConfig();
    if (data.code !== ResultEnum.SUCCESS) {
      const resultMsg = data.data ? data.data : '';
      message.error(data.mesg + '-' + resultMsg);
    }
    if (data.code === ResultEnum.SUCCESS) {
      message.success(data.mesg);
    }
    btnLoading.value = false;
  }, 500);
}
/**
 * 查看密码，重置密码模态框
 * @param record 
 * @param isShow 
 */
async function showPasswordModel(record: Recordable, isShow: boolean) {
  showPassword.value = true;
  isShowPassword.value = isShow;
  currentConfig.value = record;
  const pwd = await showPasswordApi({ id: record.id, configCode: record.configCode });
  configValue.value = pwd;
}
/**
 * 提交重置密码
 */
async function confirmValue() {
  const data = await updateValue({ id: currentConfig.value.id, configValue: encrypt(configValue.value) });
  if (data.code !== ResultEnum.SUCCESS) {
    const resultMsg = data.data ? data.data : '';
    message.error(data.mesg + '-' + resultMsg);
  }
  if (data.code === ResultEnum.SUCCESS) {
    message.success(data.mesg);
    showPassword.value = false;
    configValue.value = '';
    reloadTable();
  }
}
/**
 * 关闭密码模态窗
 */
function handleCancelShowPassword() {
  showPassword.value = false;
}
/**
 * 打开更换图片模态框
 * @param record 
 */
function handlechangePicModel(record: Recordable) {
  changePicModel.value = true;
  currentConfig.value = record;
  let pictureList: any = [];
  pictureList.push(record.configValue);
  picture.value = pictureList;
}
/**
 * 提交更换图片
 */
async function confirmPicture() {
  const data = await updateValue({ id: currentConfig.value.id, configValue: picture.value[0] });
  if (data.code !== ResultEnum.SUCCESS) {
    const resultMsg = data.data ? data.data : '';
    message.error(data.mesg + '-' + resultMsg);
  }
  if (data.code === ResultEnum.SUCCESS) {
    message.success(data.mesg);
    changePicModel.value = false;
    reloadTable();
  }
}
/**
 * 图片上传
 */
function uploadPictureChange(list: string[]) {
  picture.value = list;
}
/**
 * 关闭更换图片模态框
 */
function handleCancelPicModel() {
  changePicModel.value = false;
}
</script>

<style lang="less" scoped></style>
